package com.lxp.project.system.controller;

import com.lxp.common.utils.file.FileUtils;
import com.lxp.framework.config.SystemConfig;
import com.lxp.framework.web.controller.BaseController;
import com.lxp.framework.web.domain.AjaxResult;
import com.lxp.framework.web.page.TableDataInfo;
import com.lxp.project.system.domain.SysUpload;
import com.lxp.project.system.service.ISysUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * 附件-公用Controller
 *
 * @author equipment
 * @date 2020-08-20
 */
@RestController
@RequestMapping("/system/upload")
@Api(tags = {"附件操作相关接口"})
@Slf4j
public class SysUploadController extends BaseController {
    @Resource
    private ISysUploadService arDocumentService;

    @Value("${filePath.uploadPath}")
    private String upload_file_path;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping("")
    @ResponseBody
    public AjaxResult upload(SysUpload document, @RequestParam("file") MultipartFile file) throws UnsupportedEncodingException {
        return arDocumentService.upload(document, file);
    }

    /**
     * 文件下载
     *
     * @param id
     * @param response
     */
    @ApiOperation("文件下载")
    @GetMapping("/download/{id}")
    @ResponseBody
    public void download(@PathVariable("id") String id, HttpServletResponse response, HttpServletRequest request) {
        try {
            SysUpload arDocument = arDocumentService.findById(id);
            if (arDocument == null) {
                log.error("下载附件为空-{}", id);
                return;
            }
            String realFileName = arDocument.getName() + "." + arDocument.getFiletype();
            String fileurl = arDocument.getFileurl();
            fileurl = fileurl.substring(8);
            String filePath = SystemConfig.getProfile() + fileurl;
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 文件下载
     *
     * @param businessid
     * @param response
     */
    @ApiOperation("文件下载")
    @GetMapping("/download/attach/{businessid}")
    @ResponseBody
    public void downloadByBussesId(@PathVariable("businessid") Long businessid, HttpServletResponse response, HttpServletRequest request) {
        try {
            SysUpload arDocument = arDocumentService.findByBusinessId(businessid);
            if (arDocument == null) {
                log.error("下载附件为空-{}", businessid);
                return;
            }
            String realFileName = arDocument.getName() + "." + arDocument.getFiletype();
            String fileurl = arDocument.getFileurl();
            fileurl = fileurl.substring(8);
            String filePath = SystemConfig.getProfile() + fileurl;
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 文件删除
     *
     * @param id
     */
    @ApiOperation("文件删除")
    @DeleteMapping("{id}")
    @ResponseBody
    public AjaxResult delete(@PathVariable("id") String id) {
        return arDocumentService.deleteFile(id);
    }

    /**
     * 获取文件列表
     *
     * @return
     */
    @ApiOperation("获取文件列表")
    @GetMapping("")
    public TableDataInfo fileList(SysUpload arDocument, TableDataInfo tableSupport) {
        return arDocumentService.getPageList(arDocument, tableSupport);
    }

    @ApiOperation("获取集合")
    @GetMapping(value = "/getList")
    public AjaxResult getList(String filetype, String businessid) {
        return arDocumentService.getListByBusinessId(filetype, businessid);
    }

    /**
     * 查询附件
     *
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping("/get/{id}")
    @ApiOperation("查询附件")
    public AjaxResult imageView(@PathVariable("id") String id) {
        return AjaxResult.success(arDocumentService.findById(id));
    }

    /**
     * 图片预览
     *
     * @param id
     * @return
     * @throws Exception
     */
    @ApiOperation("图片预览")
    @GetMapping("view/{id}")
    public ResponseEntity<byte[]> responseEntityView(@PathVariable("id") String id) throws Exception {
        return arDocumentService.pictureShow(id, upload_file_path);
    }

    /**
     * 图片查看
     *
     * @param id
     * @return
     * @throws Exception
     */
    @ApiOperation("图片查看")
    @GetMapping("/imageView/{id}")
    public void imageView(@PathVariable("id") String id, HttpServletResponse response) throws Exception {
        arDocumentService.imageShow(id, upload_file_path, response);
    }
}
